package me.edzh.spring.bootstrap.utils.data;

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Excel {

    private Workbook workbook;
    private Sheet sheet;
    private AtomicInteger currentRow = new AtomicInteger(1);
    public Excel(List<String> headerFields) {
        workbook = new SXSSFWorkbook(100);
        sheet = workbook.createSheet("sheet1");

        Row row_h = sheet.createRow(0);
        //设置表头
        for (int i = 0; i < headerFields.size(); i++) {
            Cell cell = row_h.createCell(i);
            //单元格宽度
//            sheet.setColumnWidth(i, 3000);
            cell.setCellValue(headerFields.get(i));
        }
    }

    public void addRow(List<String> row) {
        Row row_h = sheet.createRow(currentRow.getAndIncrement());

        for (int i = 0; i < row.size(); ++i) {
            Cell cell = row_h.createCell(i);
            cell.setCellValue(row.get(i));
        }
    }

    public void addRows(List<List<String>> rows) {
        rows.parallelStream().peek(this::addRow);
    }

    public byte[] export() {
        ByteArrayOutputStream os = null;
        try {
            os = new ByteArrayOutputStream();
            workbook.write(os);
            return os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

